#!/usr/bin/env python3
"""
手动触发监控任务
"""

import sys
import time
sys.path.append('.')

def trigger_monitoring():
    """手动触发监控任务"""
    try:
        from app.celery_app import celery_app
        
        print("Triggering monitoring task...")
        
        # 提交监控任务
        result = celery_app.send_task("simple_check_monitors")
        print(f"Task submitted: {result.id}")
        
        # 等待结果
        print("Waiting for task completion...")
        for i in range(60):  # 等待最多60秒
            time.sleep(1)
            if result.ready():
                task_result = result.result
                print(f"Task completed: {task_result}")
                
                if task_result and task_result.get('status') == 'completed':
                    print(f"SUCCESS: Processed {task_result.get('processed', 0)} monitors")
                    print(f"Success: {task_result.get('success', 0)}")
                    print(f"Errors: {task_result.get('errors', 0)}")
                else:
                    print("Task completed but with issues")
                
                return True
            
            if i % 10 == 0:
                print(f"Still waiting... ({i+1}/60)")
        
        print(f"Task timeout. State: {result.state}")
        return False
        
    except Exception as e:
        print(f"Error: {e}")
        return False

def check_worker_status():
    """检查 Worker 状态"""
    try:
        from app.celery_app import celery_app
        
        print("Checking worker status...")
        
        inspect = celery_app.control.inspect()
        
        # 检查活跃 Worker
        stats = inspect.stats()
        if stats:
            print(f"Active workers: {len(stats)}")
            for worker in stats.keys():
                print(f"  - {worker}")
            
            # 检查注册的任务
            registered = inspect.registered()
            if registered:
                key_tasks = ["simple_check_monitors", "ultra_precision_monitor", "test_task"]
                for worker, tasks in registered.items():
                    print(f"Worker {worker} tasks:")
                    for task in key_tasks:
                        status = "OK" if task in tasks else "ERROR"
                        print(f"    {status}: {task}")
                return True
            else:
                print("ERROR: No registered tasks")
                return False
        else:
            print("ERROR: No active workers")
            return False
            
    except Exception as e:
        print(f"Error: {e}")
        return False

def main():
    """主函数"""
    print("Manual Monitor Trigger")
    print("=" * 30)
    
    # 1. 检查 Worker 状态
    worker_ok = check_worker_status()
    
    if not worker_ok:
        print("\nERROR: No workers available. Start worker first:")
        print("  python run_worker.py")
        return
    
    # 2. 触发监控任务
    print("\n" + "=" * 30)
    success = trigger_monitoring()
    
    if success:
        print("\nSUCCESS: Monitoring task completed")
    else:
        print("\nFAILED: Monitoring task failed")

if __name__ == "__main__":
    main()
